import { Injectable } from '@angular/core';
import { db } from '../../shared/common/db';
import { from, Observable, Subject } from 'rxjs';
import { Stores } from './seller.model';
import { Shop } from '../goods/goods.model';
import { Store } from '@ngxs/store';
import { Seller, SellerSelectors } from '../../store/seller';

@Injectable({
  providedIn: 'root',
})
export class SellerService {

  constructor(private store: Store) {
  }

  saveStores(value: Stores) {
    if (!!value.id) {
      return from(db.storesList.put(value));
    } else {
      delete value.id;
      return from(db.storesList.add(value));
    }
  }

  deleteStore(id: number) {
    return from(db.storesList.delete(id));
  }

  storeList() {
    return from(db.storesList.toArray());
  }

  storeDetails(id) {
    return from(db.storesList.get(id));
  }

  newShop(param: Shop) {
    delete param.id;
    return from(db.shopList.add(param));
  }

  active(id: number) {
    return from(db.storesList.toArray().then(r => {
      for (let i = 0; i < r.length; i++) {
        const obj = r[i];
        obj.current = obj.id === id;
      }
      return db.storesList.bulkPut(r);
    }));
  }

  activeInit(): Observable<boolean> | boolean {
    let subject = new Subject<boolean>();
    let activeStoreId = this.store.selectSnapshot(SellerSelectors.activeStoreId);
    if (activeStoreId !== undefined) {
      return true;
    } else {
      db.storesList.toArray().then(r => {
        let flag = true;
        for (let i = 0; i < r.length; i++) {
          const obj = r[i];
          if (obj.current === true) {
            flag = false;
            this.store.dispatch(new Seller.Active(obj.id)).subscribe(() => {
              subject.next(true);
            });
            break;
          }
        }
        if (flag) {
          this.store.dispatch(new Seller.Active(null)).subscribe(() => {
            subject.next(true);
          });
        }
      });
    }
    return subject.asObservable();
  }
}
